﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SimpleAppServer.Core;
using SimpleAppServer.Implement.Socket;
using System.Net;
using SimpleAppServer.Implement;
using System.Threading;
using System.Net.Sockets;
using SimpleAppServer.Implement.SerialPort;
namespace AppServerTest
{
    class Program
    {
        /// <summary>
        /// 测试串口服务
        /// </summary>
        static void TestSerialPort()
        {
            IAppServer server = new SerialPortServer();
            server.Received += new EventHandler<ReceivedArgs>((sender, args) =>
            {
                Console.WriteLine("收到来自{0}的消息:{1}",
                    args.Session.ToString(),
                    Encoding.Default.GetString(args.Bytes));
                Console.WriteLine("回复结果:{0}", args.Session.Send(new DefaultCommand(args.Bytes)));
            });
            server.Setup(new SerialPortConfig(5, 9600));
            if (!server.Start())
            {
                Console.WriteLine("串口服务器开启失败");
            }
            else
            {
                IAppSession session = server.CreateSession();
                for (int i = 0; i < 10; i++)
                {
                    session.Send(new DefaultCommand(Encoding.Default.GetBytes(string.Format("第{0}次测试发送!", i))));
                }
            }
        }

        static void Main(string[] command)
        {
            //测试串口服务器
            TestSerialPort();

            //测试Socket服务器
            IAppServer server =  new SocketServer();
            server.RegistSession += new EventHandler<AppSessionArgs>((sender, args) =>
            {
                Console.WriteLine("注册AppSession:{0}",
                    args.Session.ToString());
            });
            server.UnRegistSession += new EventHandler<AppSessionArgs>((sender, args) =>
            {
                Console.WriteLine("注销AppSession:{0}",
                    args.Session.ToString());
            });
            server.Received += new EventHandler<ReceivedArgs>((sender, args) =>
            {
                Console.WriteLine("收到来自{0}的消息:{1}",
                    args.Session.ToString(),
                    Encoding.Default.GetString(args.Bytes));
                Console.WriteLine("回复结果:{0}",args.Session.Send(new DefaultCommand(args.Bytes)));
            });

            //过滤列表｛TCP模式允许过滤连接客户端，UDP模式允许过滤接收端｝
            IList<EndPoint> filterList = new List<EndPoint>()
            {
                new IPEndPoint(IPAddress.Parse("192.168.0.42"),6666),
                new IPEndPoint(IPAddress.Parse("192.168.0.42"),9999),
            };
            //安装配置为UDP服务器
            //server.Setup(new SocketConfig(new IPEndPoint(IPAddress.Any, 5005),1024, new EndPointFilter(filterList)));
           
            //安装配置为TCP服务器
            server.Setup(new SocketConfig(new IPEndPoint(IPAddress.Any, 5005),
                10,
                1024,
                new SocketConfig.KeepLiveArgs(3000),
                null/*new EndPointFilter(filterList)*/));

            if (server.Start())
            {
               //进行一些Socket测试
            }
            Console.ReadLine();
        }

        static void TestUdpServer(IAppServer server)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(args =>
            {
                IAppSession session = server.CreateSession(new IPEndPoint(IPAddress.Parse("192.168.0.42"), 5005));
                for (int i = 0; i < 1000; i++)
                {
                    session.Send(new DefaultCommand(Encoding.Default.GetBytes("hello," + i)));
                }
            }));
        }

        static void TestTcpServer(IAppServer Server)
        {
            TcpFiltTest(new IPEndPoint(IPAddress.Parse("192.168.0.42"), 6666));
            TcpFiltTest(new IPEndPoint(IPAddress.Parse("192.168.0.42"), 9999));

            /*
            ThreadPool.QueueUserWorkItem(new WaitCallback(args =>
            {
                int count = 0;
                for (int i = 0; i < 10; i++)
                {
                    TcpClient client = new TcpClient();
                    try
                    {
                        client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5005));
                        bool connected = client.Connected;
                        if (connected)
                        {
                            count++;
                        }
                        Console.WriteLine("客户端{0}连接:{1},共连接成功{2}",
                            client.Client.LocalEndPoint,
                            connected,
                            count);
                        if (client.Connected)
                        {
                            Console.WriteLine("客户端发送:{0} 是否可读{1}",
                                client.Client.Send(Encoding.Default.GetBytes("hello server!")),
                                client.Client.Poll(3000, SelectMode.SelectRead));
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }));*/
        }

        static void TcpFiltTest(IPEndPoint endpoint)
        {
            TcpClient client = new TcpClient(endpoint);
            try
            {
                client.Connect(new IPEndPoint(IPAddress.Parse("192.168.0.42"), 5005));
                if (client.Connected)
                {
                    Console.WriteLine("{0}连接成功,发送结果:{1}",
                        endpoint,
                        client.Client.Send(Encoding.Default.GetBytes("你好，过滤服务器!")));

                    client.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
